package com.googlecode.olabs.clients.fileSync.contacts;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.googlecode.olabs.common.client.contact.Contact;

public class ContactLibrary {

	public static interface ContactLibraryObserver {
		void contactListUpdated();

		void contactUpdated(Contact contact);
	}

	private Collection<Contact> m_contacts;
	private Collection<ContactLibraryObserver> m_observers;

	public ContactLibrary() {
		m_contacts = new ArrayList<Contact>();
		m_observers = new ArrayList<ContactLibraryObserver>();
	}

	public void addObserver(ContactLibraryObserver observer) {
		m_observers.add(observer);
	}

	public void removeObserver(ContactLibraryObserver observer) {
		m_observers.remove(observer);
	}

	private void notifyListChanged() {
		for (ContactLibraryObserver observer : m_observers) {
			observer.contactListUpdated();
		}
	}

	private void notifyContactChanged(Contact contact) {
		for (ContactLibraryObserver observer : m_observers) {
			observer.contactUpdated(contact);
		}
	}

	public void addContact(Contact contact) {
		m_contacts.add(contact);
		notifyListChanged();
	}

	public void removeContact(Contact contact) {
		if (m_contacts.remove(contact)) {
			notifyListChanged();
		}
	}

	public int numContacts() {
		return m_contacts.size();
	}

	public Iterator<Contact> contactIterator() {
		return m_contacts.iterator();
	}

	public List<Contact> asList() {
		return new ArrayList<Contact>(m_contacts);
	}
}
